package com.wande.dataplatform.filecollection.source.impl;

import cn.hutool.extra.ssh.JschUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
import com.wande.common.core.exception.ServiceException;
import com.wande.dataplatform.filecollection.common.constant.FileCollectionConstants;
import com.wande.dataplatform.filecollection.source.IFileSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

/**
 * SFTP文件来源实现
 *
 * @author wande
 */
@Slf4j
@Component
public class SftpFileSource implements IFileSource {

    @Override
    public String getSupportedSourceType() {
        return FileCollectionConstants.SourceType.SFTP;
    }

    @Override
    public List<String> listFiles(String config) {
        JSONObject configJson = JSONUtil.parseObj(config);
        String host = configJson.getStr("host");
        int port = configJson.getInt("port", 22);
        String username = configJson.getStr("username");
        String password = configJson.getStr("password");
        String path = configJson.getStr("path", "/");
        String pattern = configJson.getStr("pattern", "*");

        List<String> files = new ArrayList<>();
        Session session = null;
        ChannelSftp channelSftp = null;

        try {
            session = JschUtil.getSession(host, port, username, password);
            channelSftp = JschUtil.openSftp(session);
            
            @SuppressWarnings("unchecked")
            Vector<ChannelSftp.LsEntry> entries = channelSftp.ls(path);
            for (ChannelSftp.LsEntry entry : entries) {
                if (!entry.getAttrs().isDir() && matchPattern(entry.getFilename(), pattern)) {
                    files.add(path + "/" + entry.getFilename());
                }
            }
            log.info("列出SFTP文件, host={}, path={}, count={}", host, path, files.size());
        } catch (Exception e) {
            throw new ServiceException("列出SFTP文件失败: " + e.getMessage());
        } finally {
            JschUtil.close(channelSftp);
            JschUtil.close(session);
        }
        return files;
    }

    @Override
    public InputStream getFileStream(String config, String filePath) {
        JSONObject configJson = JSONUtil.parseObj(config);
        String host = configJson.getStr("host");
        int port = configJson.getInt("port", 22);
        String username = configJson.getStr("username");
        String password = configJson.getStr("password");

        Session session = null;
        ChannelSftp channelSftp = null;

        try {
            session = JschUtil.getSession(host, port, username, password);
            channelSftp = JschUtil.openSftp(session);
            return channelSftp.get(filePath);
        } catch (Exception e) {
            JschUtil.close(channelSftp);
            JschUtil.close(session);
            throw new ServiceException("下载SFTP文件失败: " + filePath);
        }
    }

    @Override
    public long getFileSize(String config, String filePath) {
        JSONObject configJson = JSONUtil.parseObj(config);
        String host = configJson.getStr("host");
        int port = configJson.getInt("port", 22);
        String username = configJson.getStr("username");
        String password = configJson.getStr("password");

        Session session = null;
        ChannelSftp channelSftp = null;

        try {
            session = JschUtil.getSession(host, port, username, password);
            channelSftp = JschUtil.openSftp(session);
            SftpATTRS attrs = channelSftp.stat(filePath);
            return attrs.getSize();
        } catch (Exception e) {
            throw new ServiceException("获取SFTP文件大小失败: " + filePath);
        } finally {
            JschUtil.close(channelSftp);
            JschUtil.close(session);
        }
    }

    @Override
    public boolean testConnection(String config) {
        Session session = null;
        ChannelSftp channelSftp = null;
        try {
            JSONObject configJson = JSONUtil.parseObj(config);
            String host = configJson.getStr("host");
            int port = configJson.getInt("port", 22);
            String username = configJson.getStr("username");
            String password = configJson.getStr("password");

            session = JschUtil.getSession(host, port, username, password);
            channelSftp = JschUtil.openSftp(session);
            return channelSftp.isConnected();
        } catch (Exception e) {
            log.error("测试SFTP连接失败", e);
            return false;
        } finally {
            JschUtil.close(channelSftp);
            JschUtil.close(session);
        }
    }

    private boolean matchPattern(String fileName, String pattern) {
        if ("*".equals(pattern)) {
            return true;
        }
        String regex = pattern.replace(".", "\\.").replace("*", ".*");
        return fileName.matches(regex);
    }
}
